import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    currentDate:new Date().getTime(),
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [
      { name: '无审核通过房屋信息' },
    ],
    houseId:'',
    name:'',
    gender:1,
    mobile:'',
    visitDate:'',
    houseName:''
  },
  rules: {
    houseName:[
      {required: true, message: '请选择房屋'},
    ],
    name:[
      { required: true, message: '请填写业主名称!' },
      { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: '请检查姓名是否正确!' }
    ],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1\d{10}$/, message: '请检查手机号码是否正确!' },
    ],

    visitDate:[
      { required: true, message: '请选择预约日期!' },
    ],

  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    // 校验  rules 中定义的全部数据
    const isAllValid = this.validate()
    console.log('isAllValid',isAllValid);
    if (!isAllValid) return 

    const {houseId,name,gender,mobile,visitDate} = this.data
    const body = {houseId,name,gender,mobile,visitDate}
    const res = await wx.http.post('/visitor',body)
    console.log('提交访客信息成功',res);
    console.log('房屋id',houseId);
    // wx.reLaunch({
    //   url: '/visitor_pkg/pages/passport/index?id=' +houseId,
    // })
    wx.navigateTo({
      url: '/visitor_pkg/pages/list/index' ,
    })
  },
  async getPassHouseList(){
    const res = await wx.http.get('/house')
    console.log('审核通过的房屋',res);
    // 假设后端返回的数组中小区名字不是name，则使用数组的映射
    this.setData({
      houseList:res.data,
    })
  },
  onLoad(){
    // 查询审核通过的房屋
    this.getPassHouseList()
  },
  selectHouse(e){
    console.log('选择访问的房屋',e.detail);
    this.setData({
      houseName:e.detail.name,
      houseId:e.detail.id
    })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  confirmDate(ev){
    this.closeDateLayer()
    // console.log('选择日期',ev.detail);
    this.setData({
      // 采用封装好的时间格式化方法
      visitDate:wx.utils.formatDat(ev.detail)
    })
  },
})
